<?php

namespace Home\Controller;
use Common\Controller\Base;
use Common\Model\Model;
use Think\Controller;

class TeachController extends Base
{
    public function index()
    {
        
    } 
    
    public function tlist()
    {
        $openuid = I('get.u');
        
        $teachinfo = M('User')->where(array('openuid' => $openuid))->field("userid, openuid, nickname, uavatar, ifds, fansnum, usign")->find();
        if(empty($teachinfo['openuid']))
        {
            $this->error("不存在该导师", U("/index"));
        }
        if($teachinfo['ifds'] == 0)
        {
            $this->error("该用户不是烘焙导师", U('/index'));
        }
        $teachinfo['title'] = $teachinfo['nickname']."专栏";
   //     print_r($teachinfo['usign']);
        $teachinfo['usign'] = str_replace(PHP_EOL, "<br>", $teachinfo['usign']);
     //   print_r($teachinfo['usign']);
        $this->assign("teachinfo", $teachinfo);
        
        $iflight = I('get.iflight');
        if(empty($iflight))
        {
            $iflight = 1;
        }
        $this->assign("iflight", $iflight);
        
        $catid = 0;
        if($iflight == 1)
        {
            $cat_list = M('Teachcate')->where(array('status' => 1))->order('sort desc, catid desc')->select();
            $this->assign("cat_list", $cat_list);
            
            $catid = I('get.cate');
            if(empty($catid))
            {
                $catid = 0;
            }
            else 
            {
                $where = array('catid' => $catid);
            }
            $this->assign("catid", $catid);
        }
        elseif($iflight == 3)
        {
            $key = I('get.key');
            $type = 1;
            if($key)
            {
                $where['title'] = array("LIKE", "%{$key}%");
            }
            else
            {
                $where['title'] = "";
            }
        }
        else 
        {
            $where = array("iflight" => 1);
        }
        
        $count = M('Teachlist')->where($where)->count();
        $page = $this->Pages($count, 10);
        $pageurl='&page='.urlencode('[PAGE]');
        $page->url     = __APP__.'/teach/tlist/u/'.$teachinfo['openuid']."?iflight=".$iflight."&cate=".$catid.$pageurl;
        $list = M('Teachlist')->where($where)->order('create_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $user = M('User')->where(array('userid' => $v['userid']))->field('openuid, nickname, uavatar, ifds')->find();
                $list[$k]['openuid'] = $user['openuid'];
                $list[$k]['nickname'] = $user['nickname'];
                $list[$k]['uavatar'] = $user['uavatar'];
                $list[$k]['ds'] = $user['ifds'];
                if($iflight == 3)
                {
                    $list[$k]['title'] = str_replace($key, "<i style='color: red;'>$key</i>", $v['title']);
                }
                $list[$k]['title'] = hy_substr($list[$k]['title'], 20, true);
            }
        }
        $this->assign("list", $list);
        $this->assign("Page", $page->show());
        
        $lightlist = M('Teachlist')->where(array("iflight" => 1))->order("viewnum desc")->limit(5)->select();
        if($lightlist)
        {
            foreach($lightlist as $lk => $lv)
            {
                $lightlist[$lk]['title'] = hy_substr($lightlist[$lk]['title'], 20, true);
            }
        }
        $this->assign("lightlist", $lightlist);
        
        $works = M('Works')->where(array('status' => 1, "iftj" => 1))->order("create_time desc")->limit(5)->select();
        if($works)
        {
            foreach($works as $k => $v)
            {
                $works[$k]['content'] = hy_substr($v['content'], 20, true);
            }
        }
        $this->assign("works", $works);
        
        $is_fans = M('UserFans')->where(array('myid' => $this->userid, 'userid' => $teachinfo['userid']))->getField('status');
        if(empty($is_fans))
        {
            $is_fans = 0;   
        }
        $this->assign("is_fans", $is_fans);
        
        $ad = $this->get_ad(1);
        $this->assign("ad", $ad);
        $this->display();
    }
    
    public function addteach()
    {
        if(IS_POST)
        {
            $post = I('post.');
            if(empty($post['title'])||mb_strlen($post['title'],'utf-8')>30)
            {
                $this->error("信息标题不能为空且不能超过30个字符");
            }
            if(empty($post['type']))
            {
                $this->error("请选择所属栏目");
            }
            if(empty($post['catid']))
            {
                $this->error("请选择话题分类");
            }
            if(empty($post['content']))
            {
                $this->error("请输入话题详细内容");
            }
            $post['create_time'] = time();
            $post['iflight'] = 0;
            $post['viewnum'] = 0;
            $post['msgnum'] = 0;
            $post['userid'] = $this->userid;
            $post['ifds'] = M('User')->where(array('userid' => $this->userid))->getField("ifds");
            $content = $post['content'];
            preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', htmlspecialchars_decode($content), $match);
            $post['ifimg'] = 0;
            if($match[0])
            {
                $post['ifimg'] = 1;
            }
            $post['status'] = 1;
            $id = M('Teachlist')->add($post);
            if($id)
            {
                $openuid = M('User')->where(array('userid' => $this->userid))->getField('openuid');
                //$this->success("发布成功", U('/u/'.$openuid.'/teach'));
                $data['upoint'] = array('exp', "upoint+10");
                M('User')->where(array('userid' => $this->userid))->save($data);
                $this->success("发布成功", U('teach/'.$openuid.'/'.$id));
            }
            else
            {
                $this->error("发布失败", U('teach/addteach'));  
            }
        }
        else
        {
            if(!$this->userid)
            {
                $this->error("你还没有登录,请先登录再发表话题", U('/user/login'));
            }
            $cat_info = M('Teachcate')->where(array('status' => 1))->order('sort desc, catid desc')->select();
            $teachinfo = M('User')->where(array('openuid' => 19764))->field('userid, nickname, openuid')->find();
            $this->assign("teachinfo", $teachinfo);
            $this->assign("cat_info", $cat_info);
            $this->display();
        }
    }
    
    public function get_ad($type)
    {
        $info['center'] = M('Teachad')->where(array('status' => 1, 'position' => 1, 'type' => $type))->order('sort desc, create_time desc')->limit(5)->select();
        if($info['center'])
        {
            foreach($info['center'] as $k => $v)
            {
                if(empty($v['linkurl']))
                {
                    $info['center'][$k]['linkurl'] = "javascript:;";
                }
            }
        }
        $info['rightup'] = M('Teachad')->where(array('status' => 1, 'position' => 2, 'type' => $type))->order('sort desc, create_time desc')->limit(1)->find();
        if($info['rightup'])
        {
            if(empty($info['rightup']['linkurl']))
            {
                $info['rightup']['linkurl'] = "javascript:;";
            }
        }
        $info['rightcenter'] = M('Teachad')->where(array('status' => 1, 'position' => 3, 'type' => $type))->order('sort desc, create_time desc')->limit(1)->find();
        if($info['rightcenter'])
        {
            if(empty($info['rightcenter']['linkurl']))
            {
                $info['rightcenter']['linkurl'] = "javascript:;";
            }
        }
        $info['rightdown'] = M('Teachad')->where(array('status' => 1, 'position' => 4, 'type' => $type))->order('sort desc, create_time desc')->limit(1)->find();
        if($info['rightdown'])
        {
            if(empty($info['rightdown']['linkurl']))
            {
                $info['rightdown']['linkurl'] = "javascript:;";
            }
        }
        return $info;
    }
    
    public function detail()
    {
        $teachid = I('get.teachid');
        $openuid = I('get.openuid');
      
        $teachinfo = M('User')->where(array('openuid' => $openuid))->field("userid, nickname, openuid, uavatar")->find();
        $this->assign("teachinfo", $teachinfo);
        
        $data = M('Teachlist')->where(array('teachid' => $teachid))->find();
        if(!$data){
            $this->error('您访问的文章不存在');
        }
        
        $data['content'] = htmlspecialchars_decode($data['content']);
        $content = $data['content'];
        preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', htmlspecialchars_decode($content), $match);
        if($data['ifimg'] == 1)
        {
            $data['image'] = $match[0];
        }
        $data['title'] = hy_substr($data['title'], 30, true);
        $this->assign('data', $data);
        
        $teachuser = M('User')->where(array('userid' => $data['userid']))->field('userid, openuid, nickname, uavatar, usign, ifds')->find();
        $teachuser['usign'] = hy_substr($teachuser['usign'], 25, true);
        $this->assign("teachuser", $teachuser);
        
        $is_user = 0;
        if($data['userid'] == $this->userid)
        {
            $is_user = 1;
        }
        $this->assign("is_user", $is_user);
        
        $is_fans = M('UserFans')->where(array('myid' => $this->userid, 'userid' => $teachinfo['userid']))->getField('status');
        if(empty($is_fans))
        {
            $is_fans = 0;
        }
        $this->assign("is_fans", $is_fans);
        
        $is_coll = M('Teachfav')->where(array('infoid' => $teachid, 'userid' => $this->userid))->getField('status');
        if(empty($is_coll))
        {
            $is_coll = 0;
        }
        $this->assign("is_coll", $is_coll);
        
        $otherlist = M('Teachlist')->where(array('userid' => $data['userid'], 'status' => 1))->order("viewnum desc")->limit(7)->select();
        if($otherlist)
        {
            foreach($otherlist as $ok => $ol)
            {
                $otherlist[$ok]['title'] = hy_substr($otherlist[$ok]['title'], 20, true);
            }
        }
        $this->assign("otherlist", $otherlist);
        
        $where['infoid']=$teachid;
        $where['type']=7;
        $where['parent_id'] = 0;
        $count = M('UserMessage')->where($where)->count();
      //   $limitRows = 2; // 设置每页记录数
        $limitRows = C('YF_PAGE');
        $page = $this->ajaxpage($count,$limitRows,'#msg','ajax_div','ajax_page_div');
        
        $Model=new Model();
        $message=$Model
        ->table(array(
            C('DB_PREFIX').'user_message'=>'M',
            C('DB_PREFIX').'user'=>'U',
        )
        )
        ->where('M.userid=U.userid and M.status=true and M.infoid='.$teachid.' and M.type=7 and M.parent_id=0')//yf 0912
        ->field('M.create_time,M.content,U.nickname,U.uavatar,U.openuid,U.uprovince,U.ucity,U.userid,M.id,M.touserid,U.ifrz')
        ->order('M.create_time DESC')
        ->limit($page->firstRow . ',' . $page->listRows)
        ->select();
        
        foreach($message as $k=>$v){
            $child_temp = array();
            $child_temp = $Model->table(C('DB_PREFIX').'user_message')->field('*')->where(array('parent_id' => $v['id']))->order('create_time ASC')->select();
        
            $message[$k]['childlist'] = array();
            if($child_temp)
            {
                foreach($child_temp as $yk => $yv)
                {
                    if($yv['userid'] == 0)
                    {
                        $child_temp[$yk]['nickname'] = "烘焙圈";
                        $child_temp[$yk]['openuid'] = 0;
                    }
                    else
                    {
                        $yf_user = array();
                        $yf_user = M('User')->field('openuid, nickname, uprovince, ucity, uavatar, ifrz')->where(array('userid'=>$yv['userid']))->find();
                        $child_temp[$yk]['nickname'] = $yf_user['nickname'];
                        $child_temp[$yk]['openuid'] = $yf_user['openuid'];
                        $child_temp[$yk]['uprovince'] = $yf_user['uprovince'];
                        $child_temp[$yk]['ucity'] = $yf_user['ucity'];
                        $child_temp[$yk]['uavatar'] = $yf_user['uavatar'];
                        $child_temp[$yk]['ifrz'] = $yf_user['ifrz'];
                    }
                    if($yv['touserid'] != 0)
                    {
                        $child_temp[$yk]['touser'] = M('User')->field('openuid,nickname')->where(array('userid'=>$yv['touserid']))->find();
                    }
                    else
                    {
                        $child_temp[$yk]['touser']['nickname'] = "烘焙圈";
                        $child_temp[$yk]['touser']['openuid'] = 0;
                    }
                }
                $message[$k]['childlist'] = $child_temp;
            }
            $message[$k]['tempname'] = hy_substr($v['nickname'], 4, true);
            //$message[$k]['tempname'] = $v['nickname'];
            $message[$k]['touser'] = array();
            if(!empty($v['touserid']))
            {
                $message[$k]['touser']=M('User')->field('openuid,nickname')->where(array('userid'=>$v['touserid']))->find();
            }
        }
        unset($where['parent_id']);
        $this->msgcount=M('UserMessage')->where($where)->count();
        $this->msgtype=1;
        $this->assign('msglist',$message);
        $this->assign('page',$page->show());
        
        if(IS_AJAX){
            exit($this->fetch('msglist'));
        }
        
        $catname = M('Teachcate')->where(array('catid' => $data['catid']))->getField('catname');
       // print_r($catname);
        //print_r($this->str_split_utf8($data['title']));
        
        $str = $data['title'];
        preg_match_all('/[\x{4e00}-\x{9fff}]+/u', $str, $matches);
        $str = join('', $matches[0]);
        $temp_str = $this->str_split_utf8($str);
       // print_r($temp_str);
        $arr_str = array();
        $str_temp = array();
        for($i = 0; $i < count($temp_str); $i++)
        {
            $str_temp[] = " title LIKE '%".$temp_str[$i]."%'";
            if($i != count($temp_str) - 1)
            {
                $arr_str[] = " title LIKE '%".$temp_str[$i].$temp_str[$i+1]."%'";
            }
        }
        $arr_str = implode("or", $arr_str);
        //print_r($arr_str);
        $arr_where = "status=1 and type=1 and".$arr_str;
        
//         $likewhere['status'] = 1;
//         $likewhere['title'] = array("LIKE", "%{$catname}%");
        $works = M('Works')->where($arr_where)->order("create_time desc")->limit(5)->select();//print_r($works);
        if(!$works)
        {
            $str_temp = implode("or", $str_temp);
            $arr_where = "status=1 and type=1 and".$str_temp;
            $works = M('Works')->where($arr_where)->order("create_time desc")->limit(5)->select();//print_r($works);
        }
        
        if(!$works)
        {
            $arr_where = "status=1 and type=1";
            $works = M('Works')->where($arr_where)->order("create_time desc")->limit(5)->select();//print_r($works);
        }
        
        if($works)
        {
            foreach($works as $k => $v)
            {
                $works[$k]['content'] = hy_substr($v['content'], 20, true);
            }
        }
        
        $this->assign("works", $works);
        
        $val['viewnum'] = array('exp', "viewnum+1");
        M('Teachlist')->where(array('teachid' => $teachid))->save($val);
        $userinfo = M('User')->where(array('userid' => $this->userid))->field('openuid, uavatar, nickname')->find();
        $this->assign("userinfo", $userinfo);
        $ad = $this->get_ad(2);
        $this->assign("ad", $ad);
        $this->display();
    }
    
    public function dofav()
    {
        $post = I('post.');
        if(!$this->userid)
        {
            $this->error("你还没有登录，不能收藏该话题", U('/user/login'));    
        }
        
        if($post['userid'] == $this->userid)
        {
            $this->error("你不能收藏自己的文章");
        }
        
        $is_exist = M('Teachfav')->where(array('infoid' => $post['teachid'], 'userid' => $this->userid))->count();
        if($is_exist > 0)
        {
            if($post['type'] == 'addfav')
            {
                $data['status'] = 1;
                $data['create_time'] = time();
            }
            elseif($post['type'] == 'cancelfav')
            {
                $data['status'] = 0;
            }
            $id = M('Teachfav')->where(array('infoid' => $post['teachid'], 'userid' => $this->userid))->save($data);
        }
        else 
        {
            $data['type'] = 7;
            $data['userid'] = $this->userid;
            $data['infoid'] = $post['teachid'];
            $data['create_time'] = time();
            $data['status'] = 1;
            $data['ifread'] = 0;
            $data['is_del'] = 0;
            $id = M('Teachfav')->add($data);
        }
        if($post['type'] == 'addfav')
        {
            if($id)
            {
                $this->success("收藏成功");
            }
            else 
            {
                $this->error("收藏失败");   
            }
        }
        elseif($post['type'] == 'cancelfav')
        {
            if($id)
            {
                $this->success("取消收藏成功");
            }
            else 
            {
                $this->error("取消收藏失败");
            }
        }
    }
    
    public function editteach()
    {
        if(IS_POST)
        {
            $post = I('post.');
            $teachid = $post['teachid'];
            unset($post['teachid']);
            if(empty($post['title'])||mb_strlen($post['title'],'utf-8')>30)
            {
                $this->error("信息标题不能为空且不能超过30个字符");
            }
            if(empty($post['type']))
            {
                $this->error("请选择所属栏目");
            }
            if(empty($post['catid']))
            {
                $this->error("请选择话题分类");
            }
            if(empty($post['content']))
            {
                $this->error("请输入话题详细内容");
            }
            $post['create_time'] = time();
            $post['ifds'] = M('User')->where(array('userid' => $this->userid))->getField("ifds");
            $content = $post['content'];
            preg_match('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', htmlspecialchars_decode($content), $match);
            $post['ifimg'] = 0;
            if($match[0])
            {
                $post['ifimg'] = 1;
            }
           // $post['status'] = 1;
            $id = M('Teachlist')->where(array('teachid' => $teachid))->save($post);
            if($id)
            {
                $openuid = M('User')->where(array('userid' => $this->userid))->getField('openuid');
               // $this->success("编辑成功", U('/u/'.$openuid.'/teach'));
                $this->success("编辑成功", U('teach/'.$openuid.'/'.$teachid));
            }
            else
            {
                $this->error("编辑失败", U('teach/editteach/id/'.$teachid));
            }
        }
        else 
        {
            $teachid = I('get.id');
            $data = M('Teachlist')->where(array('teachid' => $teachid))->find();
            if(!$data)
            {
                $this->error("该话题文章不存在", U('/index'));
            }
            $data['content'] = htmlspecialchars_decode($data['content']);
            $this->assign("data", $data);
            
            if($this->userid != $data['userid'])
            {
                $this->error("你没有权限编辑该话题文章", U('/index'));
            }
            
            $cat_info = M('Teachcate')->where(array('status' => 1))->order('sort desc, catid desc')->select();
            
            $this->assign("cat_info", $cat_info);
            $teachinfo = M('User')->where(array('openuid' => 19764))->field('userid, nickname, openuid')->find();
            $this->assign("teachinfo", $teachinfo);
            
            $this->display();
        }
    }
    
    public function delteach()
    {
        $post = I('post.');
        if($this->userid != $post['userid'])
        {
            $this->error("你没有权限删除该话题文章");
        }
        
        $id = M('Teachlist')->where(array('teachid' => $post['teachid']))->delete();
        if($id)
        {
            $data['upoint'] = array('exp', 'upoint-10');
            M('User')->where(array('userid' => $this->userid))->save($data);
            if($post['type'] == 'ucenter')
            {
                $this->success("删除成功", U('/u/'.$post['openuid'].'/teach'));
            }
            else 
            {
                $this->success("删除成功", U('teach/tlist/u/'.$post['openuid']));
            }
        }
        else 
        {
            $this->error("删除失败");
        }
    }
    
    public function str_split_utf8($str){
        $split=1;
        $array=array();
        for($i = 0;$i<strlen($str);){
            $value=ord($str[$i]);
            if($value>127){
                if($value>=192&&$value<=223) $split=2;
                elseif($value>=224 && $value<=239) $split=3;
                elseif($value>=240 && $value<=247) $split=4;
            }else{
                $split=1;
            }
            $key=NULL;
            for($j=0;$j<$split;$j++,$i++){
                $key.=$str[$i];
            }
            array_push($array,$key);
        }
        return $array;
    }
    
}